package jdly.water.api.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import jdly.water.api.common.service.R;
import jdly.water.entity.system.TUser;

@RestController
public class UserController {
	/**
	 * 登录方法
	 * 
	 * @param userInfo
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public String login(TUser userInfo) {
		JSONObject jsonObject = new JSONObject();
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getUpassword());
		try {
			subject.login(token);
			jsonObject.put("token", subject.getSession().getId());
			jsonObject.put("msg", "登录成功");
			jsonObject.put("success", true);
		} catch (IncorrectCredentialsException e) {
			jsonObject.put("msg", "密码错误");
			jsonObject.put("success", false);
		} catch (LockedAccountException e) {
			jsonObject.put("msg", "登录失败，该用户已被冻结");
			jsonObject.put("success", false);
		} catch (AuthenticationException e) {
			jsonObject.put("msg", "该用户不存在");
			jsonObject.put("success", false);
		} catch (Exception e) {
			jsonObject.put("msg", "服务器异常");
			jsonObject.put("success", false);
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	@RequestMapping("/unauth")
	@ResponseBody
	public R unauth() {
		R json = R.ok();
		json.put("code", "1000000");
		json.put("success", false);
		json.put("msg", "登录失效，请重新登录");
		return json;
	}
	

}
